package com.scm.parser;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;

import scm.quote.jaxb.DoppiaChance;
import scm.quote.jaxb.GNG;
import scm.quote.jaxb.Handicap;
import scm.quote.jaxb.Match;
import scm.quote.jaxb.Risultato1Tempo;
import scm.quote.jaxb.RisultatoFinale;
import scm.quote.jaxb.SCMBean;
import scm.quote.jaxb.Segna;
import scm.quote.jaxb.UO15;
import scm.quote.jaxb.UO25;
import scm.quote.jaxb.UO35;

import com.scm.error.SCPException;
import com.scm.property.PropertyConfig;
import com.scm.property.IPropertyConfig;


public class TEXTParserQuoteJaxb implements QuoteParserJaxb{
	private Logger log = Logger.getLogger(TEXTParserQuoteJaxb.class);

	private String exportFile = null;
	
	public TEXTParserQuoteJaxb(){
		IPropertyConfig property = new PropertyConfig();
		exportFile =	property.getStringFileEsport();
	}
	
	public SCMBean getBeanScm() throws SCPException{
		SCMBean totalQuote =  startParser();
		return totalQuote;
	}
	
	private SCMBean startParser() throws SCPException{
		SCMBean scmObject = new SCMBean();
		DataInputStream inputStream =  null;
		BufferedReader br =  null;
		FileInputStream fileInput = null;
		try{
		  fileInput = new FileInputStream(exportFile);
      	  inputStream = new DataInputStream(fileInput);
      	  br = new BufferedReader(new InputStreamReader(inputStream));
      	  String strLine;
		  String eccex = null;
		  
      	  while ((strLine = br.readLine()) != null)   {
      		
      		if(strLine.matches("\\d+/\\d+")){
  		  		eccex = strLine;
  		  	}
      		else if(strLine.matches("\\d+/\\d+.*")){
      			scmObject.getMatch().add(loadingAvvenimento(strLine));
  		  	}
  		  	
  		    if(eccex !=  null){
  			  		if(strLine.contains(",") && strLine.contains(".")){

  			  		Pattern intsOnly = Pattern.compile("\\s+\\d+");
  			  		Matcher makeMatch = intsOnly.matcher(strLine);
  			  		makeMatch.find();
  			  		String inputInt = makeMatch.group();	
  			  		int index = strLine.indexOf(inputInt.trim());
  			  		String newStr = strLine.substring(index);	
  			  		scmObject.getMatch().add(loadingAvvenimento(eccex+" "+newStr));
  			  		eccex = null;
  			  	}
  		    }
      	  }
      	  inputStream.close();
      	  log.debug("Size:"+scmObject.getMatch().size());
      	  
      	  
      	}catch (Exception e){
      		throw new SCPException("PARSER_EXPORT_FAILED",777,"Parser Export Fallito!"+e);
      	 
      	}

		return scmObject;
	}
	
	private Match loadingAvvenimento(String riga){
		try{
		riga = riga.replaceAll("Schalke 04","Schalke");
		log.info("->"+riga);
	/*	Pattern intsOnly = Pattern.compile("\\d*,\\d\\d*");
	  	Matcher makeMatch = intsOnly.matcher(riga);
	  	makeMatch.find();
	  	String inputInt = makeMatch.group();	
	*/
		
		
		String t1 = riga.replaceAll("\\s+"," ");
		String []t2 = t1.split(" ");
		String d = "";
		for(int index = 5 ; index < t2.length ; index++){
			d=d+" "+t2[index];	
		}
		Pattern intsOnly2 = Pattern.compile("([a-zA-Z]+\\s+)*");
		Matcher makeMatch2 = intsOnly2.matcher(d.trim());
		makeMatch2.find();
		String inputInt2 = (makeMatch2.group()).trim();	
			
	    String []test2 = inputInt2.split(" ");
		String finale = test2[test2.length-1];
			
		String primatest = riga.substring(0,riga.indexOf(finale));
		String dopotest = riga.substring(riga.indexOf(finale));

		Pattern intsOnly3 = Pattern.compile("([a-zA-Z]+\\s+)");
		Matcher makeMatch3 = intsOnly3.matcher(dopotest);
		makeMatch3.find();
		String inputInt3 = (makeMatch3.group());		
 		String dopo = riga.substring(riga.indexOf(inputInt3)+inputInt3.length(),riga.length());
 		String prima = primatest+inputInt3;
		
	 // 	String prima = riga.substring(0,riga.indexOf(inputInt));
	 // 	String dopo = riga.substring(riga.indexOf(inputInt));
		
	 /* 	if((prima.trim()).matches(".*\\d+$")){
	  		Pattern intsOnly2 = Pattern.compile("\\d+$");
		  	Matcher makeMatch2 = intsOnly2.matcher(prima.trim());
		  	makeMatch2.find();
		  	String inputInt2 = (makeMatch2.group()).trim();	
		  	dopo =inputInt2+"     "+dopo;
	  	}*/
 		
	  	List<String> infoList = new ArrayList<String>(); 
	  	
	  	prima = prima.replaceAll("\\s+|\\s+"," ");
		
		String[] sliptPrima = prima.split(" ");
		infoList.add(sliptPrima[0]);
		infoList.add(sliptPrima[1]);
		infoList.add(sliptPrima[2]);
		infoList.add(sliptPrima[3]);
		infoList.add(sliptPrima[4]);
		String sq = "";
	    for(int ind=5;ind<sliptPrima.length;ind++){
	    	sq=sq+" "+sliptPrima[ind];
	    }
	    infoList.add(sq);
	    
	 	String formatting = dopo.replace(" ","|");
	 	
	 	formatting = formatting.replace("||||||||||||||||||||||||||||||||||||||||||||||", "|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00");//46
	 	formatting = formatting.replace("||||||||||||||||||||||||||", "|0,00|0,00|0,00|0,00|0,00|0,00|0,00|0,00|");//27
	 	formatting = formatting.replace("||||||||||||||||||||||", "|0,00|0,00|0,00|0,00|0,00|0,00|0,00|");//22
		formatting = formatting.replace("||||||||||||||||||||", "|0,00|0,00|0,00|0,00|0,00|0,00|");//20
		formatting = formatting.replace("||||||||||||||||||","|0,00|0,00|0,00|0,00|0,00|");//18
		formatting = formatting.replace("||||||||||||||", "|0,00|0,00|0,00|0,00|");//14
		formatting = formatting.replace("||||||||||||", "|0,00|0,00|0,00|");//12
		formatting = formatting.replace("||||||||||", "|0,00|0,00|");//10
		formatting = formatting.replace("||||||||", "|0,00|0,00|");//8
		formatting = formatting.replace("||||||", "|0,00|");//6
		formatting = formatting.replace("|||||", "|");//5
		formatting = formatting.replace("||||", "$");//4
		formatting = formatting+"$";
		String[] slipts =  formatting.split("\\|");		
		
		int indexFloat = 0;
		List<String> quoteList = new ArrayList<String>(); 
		for (int index = 0; index < slipts.length; index++) {
			String temp = slipts[index];

			try {
				Float.parseFloat(temp.replace(",", "."));
				quoteList.add(indexFloat, temp);
				indexFloat++;
			} catch (NumberFormatException e) {
				String[] occorrenze = temp.split("\\$");
				if (occorrenze.length == 2) {
					quoteList.add(indexFloat, occorrenze[0]);
					indexFloat++;
					quoteList.add(indexFloat, occorrenze[1]);
					indexFloat++;
				} else if (occorrenze.length == 3) {
					quoteList.add(indexFloat, occorrenze[0]);
					indexFloat++;
					quoteList.add(indexFloat, occorrenze[1]);
					indexFloat++;
					quoteList.add(indexFloat, "0,00");
					indexFloat++;
					quoteList.add(indexFloat, occorrenze[2]);
					indexFloat++;
				} else if (occorrenze.length == 4) {
					quoteList.add(indexFloat, occorrenze[0]);
					indexFloat++;
					quoteList.add(indexFloat, occorrenze[1]);
					indexFloat++;
					quoteList.add(indexFloat, "0,00");
					indexFloat++;
					quoteList.add(indexFloat, occorrenze[2]);
					indexFloat++;
					quoteList.add(indexFloat, occorrenze[3]);
					indexFloat++;
				}
			}
		}
		Match avvMatch = new Match();
		try{
			avvMatch.setDataMatch(infoList.get(0)+" "+infoList.get(1));
			avvMatch.setTipoAvv(infoList.get(2));
			avvMatch.setAvvenimento(infoList.get(3));
			avvMatch.setPalinsesto(infoList.get(4));
			avvMatch.setSquadraHome(infoList.get(5));
			avvMatch.setSquadraGuest(infoList.get(5));
			
			RisultatoFinale rf = new RisultatoFinale();
			rf.setR1(replaceZero(quoteList.get(0)));
			rf.setRx(replaceZero(quoteList.get(1)));
			rf.setR2(replaceZero(quoteList.get(2)));
			avvMatch.setRisultatoFinale(rf);
		
			Risultato1Tempo r1t = new Risultato1Tempo();
			r1t.setR1(replaceZero(quoteList.get(3)));
			r1t.setRx(replaceZero(quoteList.get(4)));
			r1t.setR2(replaceZero(quoteList.get(5)));
			avvMatch.setRisultato1Tempo(r1t);
			
			Handicap hdc = new Handicap();
			hdc.setR1(replaceZero(quoteList.get(6)));
			hdc.setRx(replaceZero(quoteList.get(7)));
			hdc.setR2(replaceZero(quoteList.get(8)));
			avvMatch.setHandicap(hdc);
			
			DoppiaChance db = new DoppiaChance();
			db.setR1(replaceZero(quoteList.get(9)));
			db.setRx(replaceZero(quoteList.get(10)));
			db.setR2(replaceZero(quoteList.get(11)));
			avvMatch.setDoppiaChance(db);

			UO15 uo15 = new UO15();
			uo15.setRu(replaceZero(quoteList.get(12)));
			uo15.setRo(replaceZero(quoteList.get(13)));
			avvMatch.setUO15(uo15);
			
			UO25 uo25 = new UO25();
			uo25.setRu(replaceZero(quoteList.get(14)));
			uo25.setRo(replaceZero(quoteList.get(15)));
			avvMatch.setUO25(uo25);
			
			UO35 uo35 = new UO35();
			uo35.setRu(replaceZero(quoteList.get(16)));
			uo35.setRo(replaceZero(quoteList.get(17)));
			avvMatch.setUO35(uo35);
			
			GNG gng = new GNG();
			gng.setG(replaceZero(quoteList.get(18)));
			gng.setNg(replaceZero(quoteList.get(19)));
			avvMatch.setGNG(gng);
			
			Segna sga = new Segna();
			sga.setS1G(replaceZero(quoteList.get(20)));
			sga.setS1Ng(replaceZero(quoteList.get(21)));
			sga.setS2G(replaceZero(quoteList.get(22)));
			sga.setS2Ng(replaceZero(quoteList.get(23)));
			avvMatch.setSegna(sga);
			
		}catch(IndexOutOfBoundsException ex){
			log.error(riga.replace(" ","|"));
			log.error("PRIMA : "+prima+"|");
			log.error("DOPO  : "+dopo+"|");
		//	log.error("formatting:"+formatting);
		//	log.error("dopo.replace "+dopo.replace(" ","|"));
		//	for(String quote: quoteList){
		//		log.error("-"+quote);
		//	}
		}
			return avvMatch;
		
		}catch(java.lang.ArrayIndexOutOfBoundsException d){
			log.error(d);
			
		}
		return null;
	}
	
	private String replaceZero(String zero){
		if(zero!= null && zero.endsWith("0,00"))
			return "-";
		return zero;
	}
	
}
